package com.shyroke.realms;

import java.util.Iterator;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.shyroke.dao.UserDao;
import com.shyroke.entity.User;

public class MyRealm extends AuthorizingRealm {

	UserDao userDao = new UserDao();

	/**
	 * 为当前登录的用户授予角色和权限
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		String userName=principals.getPrimaryPrincipal().toString();
		
		/**
		 * 根据用户名获取当前用户的角色和权限集合
		 */
		
		Set<String> roles=userDao.getRolesByName(userName);
		Set<String> objectPermissions=userDao.getPermissionsByName(userName);
		
		/**
		 * 为该用户设置角色和权限
		 */
		SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
		
		authorizationInfo.addRoles(roles);
		
		authorizationInfo.setStringPermissions(objectPermissions);
		
		return authorizationInfo;
	}

	/**
	 * 验证当前登录的用户
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userName = token.getPrincipal().toString();

		User user = userDao.getUserByName(userName);

		if (user != null) {
			/*
			 * 说明用户登录成功
			 */
			AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassWord(),
					getName());
			return authenticationInfo;
		}

		return null;
	}

}
